import { EventSourcePolyfill } from "event-source-polyfill";
import axios from "axios";


let baseUrl = process.env.REACT_APP_BASE_URL;

// 创建axios实例 ，设置默认请求配置
const instance = axios.create({
    timeout: 60000,//超时时间
    baseURL: baseUrl//基本路由
})

//统一设置post请求头
instance.defaults.headers.post['Content-Type'] = "application/json";


//请求拦截器
instance.interceptors.request.use(config => {
    var token = `Bearer ZXlKMGVYQWlPaUpLVjFRaUxDSmhiR2NpT2lKSVV6STFOaUo5LmV5SjBkQ0k2TkN3aVlYVmtJam9pTXpobVlUY3lOMkpoTUdNeU5HVXhNR0V4T0dZeU1UZzFZVEE0TkRObVkyWWlMQ0pzZFNJNkltaHplVEkxTVRBME15SXNJbVY0Y0NJNk1qRTBOVGc0T0RBd01Dd2lkWElpT2pJc0ltcDBhU0k2SWtGUVNWOVVUMHRGVGw4ek9HWmhOekkzWW1Fd1l6STBaVEV3WVRFNFpqSXhPRFZoTURnME0yWmpaaTAwSW4wLlFZQXFJQjJVeHZlc2gxU3JVLW10aEp0OF8tYzRoRF9Dc1VXelYxUEdLcjg`;//获取缓存中的token

    if (token) {
        config.headers['Authorization'] = token;//在请求头中加上token
    }


    return config;
}, error => {
    console.log("error请求错误", error)
    return Promise.reject(error)
})


// 响应拦截 判断数据是否正常完好，再把数据返回到发请求的地方
instance.interceptors.response.use(response => {
    console.log("响应拦截处：\n", response)
    if (response.status === 200) {
        const res = response.data;
        if (res.code === 401) {
            console.log(res.msg);
            return Promise.reject(response.data)
        }
        debugger
        return Promise.resolve(response.data)
    } else {
        return Promise.reject(response.data.msg)
    }
}, error => {
    //请求报错的回调，对不同状态码进行处理
    console.log("请求报错：\n", error)
    if (error.response) {
        if (error.response.status === 401) {

            // this.props.history.push("/login");//跳转回到登录页面
        }
        return Promise.reject(error)
    } else {
        return Promise.reject("请求超时，请重试");
    }
})



// 可借助 querystring 等工具快速格式化参数，此处为了方便展示
const query = {
    prompt:
        "请扮演一个解决方案专家，无论我提出什么问题，请直接给出方案，不要有其他多余的文字",
    question: "怎么把 5 个苹果合理地分给 6 个小朋友",
    cid: "E103C5308CB849768D079DF2****",
    stream: true
};
const Authorization = "ZXlKMGVYQWlPaUpLVjFRaUxDSmhiR2NpT2lKSVV6STFOaUo5LmV5SjBkQ0k2TkN3aVlYVmtJam9pTXpobVlUY3lOMkpoTUdNeU5HVXhNR0V4T0dZeU1UZzFZVEE0TkRObVkyWWlMQ0pzZFNJNkltaHplVEkxTVRBME15SXNJbVY0Y0NJNk1qRTBOVGc0T0RBd01Dd2lkWElpT2pJc0ltcDBhU0k2SWtGUVNWOVVUMHRGVGw4ek9HWmhOekkzWW1Fd1l6STBaVEV3WVRFNFpqSXhPRFZoTURnME0yWmpaaTAwSW4wLlFZQXFJQjJVeHZlc2gxU3JVLW10aEp0OF8tYzRoRF9Dc1VXelYxUEdLcjg=";
const getStream = ({
    before = Function,
    params = Object,
    success = Function,
    failure = Function,
    complate = Function
}) => {
    const { question = String, prompt = String, cid = String, stream = true } = params
    const source = new EventSourcePolyfill(
        `https://api.devbit.cn/ai/api/ai/chat?question=${question}&prompt=${prompt}&cid=${cid}&stream=${stream}`,
        {
            headers: {
                // "Content-Type": 'text/event-stream',
                Accept: "*/*",
                Authorization: Authorization
            }
        }
    );
    source.onopen = event => {
        console.log("onopen", event);
    };
    source.onmessage = event => {
        if (event.data === "[DONE]") {
            source.close();
            complate();
        }
        if (event.data) {
            const data = JSON.parse(event.data);
            const text = data.message.content.parts.join("");
            console.log(text);
            success(data);
            success(text);
            // 注意此处data为流式返回，通常每次只有1-2个字符，需要根据不同场景手动拼接
        }
    };
    source.onerror = event => {
        console.log("error", event);
        failure(event);
    };
}


// 封装get请求
const get = (url, params, config = {}) => {
    return new Promise((resolve, reject) => {
        instance({
            method: "get",
            url,
            params,
            ...config
        }).then(response => {
            resolve(response)
        }).catch(error => {
            reject(error)
        })
    })
}

//封装post请求
const post = (url, data, config = {}) => {
    return new Promise((resolve, reject) => {
        instance({
            method: 'post',
            url,
            data,
            ...config
        }).then(response => {
            resolve(response)
        }).catch((error) => {
            reject(error)
        })
    })
}



// 封装文件上传(二进制流上传)
const upload = ({
    url = "",
    data,
    params = {},
    headers = {}
}) => {
    return new Promise((resolve, reject) => {
        instance({
            method: "POST",
            url,
            params: { ...params },
            data,
            headers: {
                "Content-Type": "multipart/form-data",
                ...headers
            }
        }).then(response => {
            resolve(response)
        }).catch(error => {
            reject(error)
        })
    })
}


const http = {
    getStream: getStream,
    post: async ({
        url = String,
        params = Object,
        headers = Object,
        before = () => { },
        success = () => { },
        failure = () => { },
        complete = () => { }
    }) => {
        try {
            before();
            const res = await post(url, { ...params, }, headers)
            if (res.errorCode === "0000") {
                success(res)
            } else {
                failure(res.message)
            }
        } catch (error) {
            console.log(error)
            failure(error.msg)
        } finally {
            complete()
        }
    },
    get: async ({
        url = String,
        params = Object,
        before = Function,
        success = Function,
        failure = Function,
        complete = Function
    }) => {
        before()
        try {

            const res = await get(url, {
                ...params,
            })

            if (res.errorCode === "0000") {
                success(res)
            } else {
                failure(res.errorDesc)
            }
        } catch (error) {
            console.log(error)
            failure("网络连接失败")
        } finally {
            complete()
        }
    },
    upload: async ({
        url = String,
        params = Object,
        before = Function,
        success = Function,
        failure = Function,
        complete = Function,
        formData = new FormData()
    }) => {
        before();
        try {
            let fmData = formData;
            fmData.append(params.filename || 'file', params.file)
            const res = await upload({
                url,
                data: fmData,
            })
            console.log("文件上传结果：", res)
            if (res.errorCode === '0000') {
                success(res)
            } else {
                failure(res.errorDesc)
            }
        } catch (error) {
            console.log("文件上传catch：", error)
            failure("文件无法上传，网络连接失败")
        } finally {
            complete()
        }
    }
}

export default http;